import _ from 'lodash';
import Promise from 'promise';
import * as ResultMsg from '../constrants/ResultMsg';
import { TopicCollectModel } from '../models';

export function count(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  return TopicCollectModel.count(conditions).setOptions(options);
}

export function find(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = TopicCollectModel.find(conditions).setOptions(options);
  return query.exec();
}

export function findOne(appId, userId, topicId) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof userId !== 'string' && typeof userId !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof topicId !== 'string' && typeof topicId !== 'object') throw new Error(ResultMsg.NO_ID);

  const query = TopicCollectModel.findOne({appId: appId, user_id: userId, topic_id: topicId });
  return query.exec();
}

export function create(appId, userId, topicId) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof userId !== 'string' && typeof userId !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof topicId !== 'string' && typeof topicId !== 'object') throw new Error(ResultMsg.NO_ID);

  const doc = new TopicCollectModel();
  doc.appId = appId;
  doc.user_id = userId;
  doc.topic_id = topicId;
  return doc.save();
}

export function remove(appId, userId, topicId) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof userId !== 'string' && typeof userId !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof topicId !== 'string' && typeof topicId !== 'object') throw new Error(ResultMsg.NO_ID);

  return TopicCollectModel.remove({appId, user_id: userId, topic_id: topicId });
}

